package czk.concrent.threadpool.method;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * invokeAll执行所有线程的demo
 * 执行几何中所有的任务
 * @Author:ChenZhangKun
 * @Date: 2020/7/5 17:21
 */
public class InvokeAll {
    public static void main(String[] args) throws InterruptedException {
        // 创建线程数
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 执行任务，利用lambda表达式计算
        // 接收线程的集合
        List<Future<String>> futures = executorService.invokeAll(Arrays.asList(
                () -> {
                    System.out.println("第一个任务开始了");
                    Thread.sleep(1 * 1000);
                    return "1";
                },

                () -> {
                    System.out.println("第二个任务开始了");
                    Thread.sleep(2 * 1000);
                    return "2";
                },
                () -> {
                    System.out.println("第三个任务开始了");
                    Thread.sleep(3 * 1000);
                    return "3";
                }
        ));
        futures.forEach(x -> {
            try {
                System.out.println(x.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
